package com.jrx.anytxn.transaction.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.service.partner.IPmMerchantTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.ribbon.config.GrayVersionConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlWaivePaymentLog;
import com.jrx.anytxn.transaction.entity.TlWaivePaymentMapping;
import com.jrx.anytxn.transaction.service.IDealGatewayService;
import com.jrx.anytxn.param.service.system.ISequenceNumberService;
import com.jrx.anytxn.transaction.service.ISmsService;
import com.jrx.anytxn.transaction.service.IWaivePaymentLogService;
import com.jrx.anytxn.transaction.utils.PaymentUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 还款流水service实现
 *
 * @author : zhenghaopu
 * 2019/10/21
 */
@Service
public class WaivePaymentLogServiceImpl implements IWaivePaymentLogService {

    private static final Logger logger= LoggerFactory.getLogger(WaivePaymentLogServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;
    @Lazy
    @Autowired
    private IInnerGatewayService innerGatewayService;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IDealGatewayService dealGatewayService;
    @Autowired
    private ISmsService iSmsService;
    @Autowired
    private IPmMerchantTableService pmMerchantTableService;
    @Autowired
    private GrayVersionConfig grayVersionConfig;
    @Autowired
    ISequenceNumberService sequenceNumberService;

    @Override
    public TlWaivePaymentLog buildTlWaivePaymentLog(String paymentType, CustomerRes customerRes,
                                          BigDecimal debtAmount, Date businessDate, PrProductTable product) throws TxnBizException {
        TlWaivePaymentLog tlWaivePaymentLog = new TlWaivePaymentLog();
        try {
            tlWaivePaymentLog.setId(segmentService.getId(TransBizConstant.TL_WAIVE_PATMENT_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlWaivePaymentLog.setSeqNo(TransBizConstant.PAYMENT_LOG_SEQ_PREFIX+ SeqUtils.getSNByLength(TransBizConstant.PAYMENT_LOG_SEQ_RADOM_LENGTH));//流水号	唯一索引 PL+yyyyMMddHHmmssSSS +13位随机
        tlWaivePaymentLog.setCustomerId(customerRes.getSecondLevel().getCustomerId());//客户id	　
        tlWaivePaymentLog.setTenantId(product.getTenantId());//租户id
        tlWaivePaymentLog.setOrganizationId(customerRes.getSecondLevel().getOrganizationId());//机构号	　	同贷款订单
        tlWaivePaymentLog.setProductId(product.getProductId());//	产品id	　	同贷款订单
        tlWaivePaymentLog.setPaymentType(paymentType);
        tlWaivePaymentLog.setChargeType(TransBizConstant.PAYMENT_LOG_CHARGE_TYPE_0);//扣款种类	0=按订单扣款  1=按客户扣款	0
        tlWaivePaymentLog.setJointLoanFlag(product.getAllowJointFlag()); //联合贷标识	0=否 1=是	0
        tlWaivePaymentLog.setIsFullPay(TransBizConstant.YES_FLAG); //	是否足额扣款	0=不足额  1=足额	1
        tlWaivePaymentLog.setAmount(debtAmount);//汇款金额	　	计算出的还款金额
        tlWaivePaymentLog.setCustomerName(customerRes.getFirstLevel().getChineseName());//客户姓名

        tlWaivePaymentLog.setPayerBank("");//扣款行号
        tlWaivePaymentLog.setPayerBankName("");//扣款行名称
        tlWaivePaymentLog.setPayerAccount("");//扣款账号	　
        tlWaivePaymentLog.setPayerAccountType("");//账户类型
        tlWaivePaymentLog.setMobile(customerRes.getSecondLevel().getMobile());//手机
        tlWaivePaymentLog.setRefNo(sequenceNumberService.generateRefNo(Constant.SEQUENCE_LENGTH));
        tlWaivePaymentLog.setDescription(product.getChineseName()+ PaymentUtils.getPaymentTypeName(paymentType));//交易说明	　
        // 产品名称+逾期还款
        tlWaivePaymentLog.setAvailBalance(BigDecimal.ZERO);//余额
        tlWaivePaymentLog.setCurrency(TransBizConstant.CURRENCY_CNY);//币种	　	CNY 人民币
        tlWaivePaymentLog.setEffectDate(DateUtils.formatDate(new Date()));//生效日期	　	当前系统日期
        tlWaivePaymentLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_T); //最终状态 S 成功 F 失败 T 扣款成功，待分配 D 待发起扣款 O
        // 已发起扣款，扣款状态未知，待查询
        tlWaivePaymentLog.setChannel(customerRes.getSecondLevel().getChannel());//渠道id	　	api上送
        tlWaivePaymentLog.setBusinessDate(businessDate);//业务日期	　	当前业务日期
        tlWaivePaymentLog.setCollateDate(businessDate);//对账日期	　	当前业务日期
        tlWaivePaymentLog.setLaunchTime(new Date());//交易发起时间	　	当前时间
        tlWaivePaymentLog.setUpdateBy(TransBizConstant.SYS_OPRATE);//操作员
        tlWaivePaymentLog.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        tlWaivePaymentLog.setGrayVersion(grayVersionConfig.getCurrentVersion());
        return tlWaivePaymentLog;
    }

    @Override
    public TlWaivePaymentMapping biudTlWaivePaymentMapping(String customerId, String paymentSeqNo, String loanId,
                                                 String tenantId) throws TxnBizException{
        TlWaivePaymentMapping tlWaivePaymentMapping = new TlWaivePaymentMapping();
        try {
            tlWaivePaymentMapping.setId(segmentService.getId(TransBizConstant.TL_WAIVE_PAYMENT_MAPPING_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlWaivePaymentMapping.setTenantId(tenantId);
        tlWaivePaymentMapping.setCustomerId(customerId);//客户ID
        tlWaivePaymentMapping.setPaymentSeqNo(paymentSeqNo);//还款流水seqNo
        tlWaivePaymentMapping.setLoanId(loanId);//贷款订单
        return tlWaivePaymentMapping;
    }

}
